<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use App\Enums\Api\Response as CustomResponse;
use App\Factory\ParseException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler extends ExceptionHandler
{
    /**
     * The list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    public function render($request, $e)
    {
        if ($e instanceof ModelNotFoundException) {
            return  apiResponse(CustomResponse::SYSTEM_ERROR->value,[],CustomResponse::SYSTEM_ERROR->response());
        }
        //非允许请求方式
        if ($e instanceof MethodNotAllowedHttpException) {
            return  apiResponse(CustomResponse::SYSTEM_REQUEST_ERROR->value,[],CustomResponse::SYSTEM_REQUEST_ERROR->response());
        }
        //验证失败
        if ($e instanceof ValidationException) {
            return  apiResponse(CustomResponse::SYSTEM_CHECK_ERROR->value,[],array_values($e->validator->getMessageBag()->toArray())[0][0]);
        }
        //验证token
        if ($e instanceof AuthenticationException || $e instanceof AuthorizationException) {
            return  apiResponse(CustomResponse::TOKEN_ERROR->value,[],CustomResponse::TOKEN_ERROR->response());
        }
        //这里是为了兼容其他的一些错误
        if (Str::length($e->getMessage()) > 1 && Str::length($e->getCode()) > 1) {
            return apiResponse($e->getCode(),[], $e->getMessage());
        }
        $result = ParseException::parseException($e);
        //这里判断的原因很简单 因为可能这个code没有按照规范声明
        if (is_array($result)) {
            return apiResponse($result['code'], $result['message']);
        }
        if ($e instanceof NotFoundHttpException) {
            return  apiResponse(CustomResponse::SYSTEM_NOT_FIND->value,[], CustomResponse::SYSTEM_NOT_FIND->response());
        }

        return parent::render($request, $e);
    }
}
